package com.lanlian.utillib;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/27 13:36
 *     desc   : 图片处理工具
 *     version: 1.0
 * </pre>
 */
public class ImageUtils {

    public static String IMAGE_SAVE_PATH = null;

    public static void init(Context context) {
        IMAGE_SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +
                context.getPackageName() + "/image" + File.separator;
        File file = new File(IMAGE_SAVE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 保存bitmap
     *
     * @param bm      图片
     * @param picName 文件名
     * @return 文件路劲
     */
    public static String saveBitmap(Bitmap bm, String picName) {
        File f = new File(IMAGE_SAVE_PATH);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(f, picName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            Log.i("IMAGE", "已经保存");
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 保存bitmap并通知系统相册更新图片
     *
     * @param bm      图片
     * @param picName 文件名
     * @return 文件路劲
     */
    public static String saveBitmap(final Context context, Bitmap bm, String picName) {
        File f = new File(IMAGE_SAVE_PATH);
        if (!f.exists()) {
            f.mkdirs();
        }
        final File file = new File(f, picName);
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                Log.i("IMAGE", "已经保存");

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(file);
                        intent.setData(uri);
                        context.sendBroadcast(intent);
                    }
                });

                return file.getPath();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return file.getPath();

    }

    /**
     * 处理旋转后的图片
     *
     * @param originPath 原图路径
     * @return 返回修复完毕后的图片路径
     */
    public static String amendRotatePhoto(String originPath, int angle, String saveName) {
        Bitmap bmp = getCompressPhoto(originPath);
        // 修复图片被旋转的角度
        Bitmap bitmap = rotateImageView(angle, bmp);
        // 保存修复后的图片并返回保存后的图片路径
        return saveBitmap(bitmap, saveName);
    }

    /**
     * 把原图按1/10的比例压缩
     *
     * @param path 原图的路径
     * @return 压缩后的图片
     */
    public static Bitmap getCompressPhoto(String path) {
        Bitmap bitmap;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = computeSampleSize(options, -1, 500 * 500);
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inPurgeable = true;
        bitmap = BitmapFactory.decodeFile(path, options);//根据Path读取资源图片
        options = null;
        return bitmap;
    }


    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public static Bitmap rotateImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }

    /**
     * 计算缩略图所需的inSampleSize
     *
     * @param options        原本Bitmap的options
     * @param minSideLength  希望生成的缩略图的宽高中的较小的值
     * @param maxNumOfPixels 希望生成的缩量图的总像素
     */
    private static int computeSampleSize(BitmapFactory.Options options,
                                         int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    /**
     * 计算缩略图所需的inSampleSize
     *
     * @param options        原本Bitmap的options
     * @param minSideLength  希望生成的缩略图的宽高中的较小的值
     * @param maxNumOfPixels 希望生成的缩量图的总像素
     */
    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) &&
                (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

}
